// pages/to_vip/to_vip.js
const app = getApp();
var router = require("../../router.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    price: 398
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var vip_type = options.type;
    var price = 398;
    if (vip_type == 2){
      price = 20000;
    }
    this.setData({
      price: price,
      vip_type: vip_type
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  buy_vip() {
    var that = this;
    app.request({
      url: router.user.vip,
      method: "POST",
      data: {
        userId: wx.getStorageSync('userInfo').id,
        vip_type: that.data.vip_type,        
      },
      success: function (data) {
        console.log(data);
        if (data.status == true) {          
          that.pay(data.info);          
        } else {
          wx.showToast({
            title: '发起支付失败',
            icon: 'none'
          });
        }
      }
    })  
  },

  pay: function (data){
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType,
      'paySign': data.paySign,
      'success': function (res) {
        console.log(res.errMsg)
        if (res.errMsg == 'requestPayment:ok') {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        }
      },
      'fail': function (res) {
        console.log(res.errMsg)
        if (res.errMsg == 'requestPayment:fail cancel') {
          wx.showToast({
            title: '取消支付',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      },
      'complete': function (res) {
      }
    })
  }
})